package com.cabal.common.util.baidu;


import com.cabal.common.util.CabalJsonUtil;

import java.util.HashMap;
import java.util.Map;

public class BaiduTranslateUtil {

    private static String TRANS_HTTP_URL = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    private static String TRANS_HTTPS_URL = "https://fanyi-api.baidu.com/api/trans/vip/translate";

    private static String APP_ID = "20200113000375141";
    private static String SECURITY_KEY = "aM4pbP_6pblZpDKTwoDn";

    public static String getTransResult(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        String unicodeValue = BaiduHttpGet.get(TRANS_HTTP_URL, params);
        System.out.println(unicodeValue);
        String result = null;
        try {
            BaiduTransDespDTO resp = CabalJsonUtil.json2pojo(unicodeValue, BaiduTransDespDTO.class);
            result = resp.getTransResultList().get(0).getDst();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);

        params.put("appid", APP_ID);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = APP_ID + query + salt + SECURITY_KEY; // 加密前的原文
        params.put("sign", BaiduMD5.md5(src));

        return params;
    }

    public static void main(String[] args) {
        String query = "高度600米";
        System.out.println(BaiduTranslateUtil.getTransResult(query, "auto", "en"));
    }

}
